package com.ruoyi.voucher.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.voucher.dto.SummaryDTO;
import com.ruoyi.voucher.vo.VoucherRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.voucher.domain.Summary;
import com.ruoyi.voucher.service.ISummaryService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 常用摘要Controller
 *
 * @author ruoyi
 * @date 2025-02-25
 */
@RestController
@RequestMapping("/summary")
public class SummaryController extends BaseController {
    @Autowired
    private ISummaryService summaryService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String SUMMARY_KEY = "summary:summaryList";


    /**
     * 导出凭证数据
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportSummaryExcel")
    public void exportSummaryExcel(HttpServletResponse response) throws IOException {
        List<Summary> summaryAll = summaryService.selectSummaryListAll();
        List<SummaryDTO> summaryDTOS = new ArrayList<>();
        for (Summary summary : summaryAll) {
            SummaryDTO build = SummaryDTO.builder().summaryId(summary.getSummaryId())
                    .summaryContent(summary.getSummaryContent())
                    .isDeleted(summary.getIsDeleted())
                    .build();
            summaryDTOS.add(build);
        }

        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("凭证数据", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 3. 创建 ExcelWriter（注意不要关闭流）
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        // 4. 导出数据
        WriteSheet mainSheet = EasyExcel.writerSheet(0, "凭证主表")
                .head(SummaryDTO.class)
                .build();
        excelWriter.write(summaryDTOS, mainSheet);

        // 6. 完成并关闭
        excelWriter.finish();


    }


    /**
     * 查询下拉框摘要数据  摘要名称模糊查询
     *
     * @param summary
     * @return
     */
    @GetMapping("/getSummaryAll")
    public AjaxResult getSummaryAll(Summary summary) {

        List<Summary> summaryAll = null;

        if (redisTemplate.hasKey(SUMMARY_KEY)) {
            String s = redisTemplate.opsForValue().get(SUMMARY_KEY);
            summaryAll = JSON.parseArray(s, Summary.class);
        } else {
            summaryAll = summaryService.getSummaryAll(summary);
        }

        return success(summaryAll);
    }


    /**
     * 查询常用摘要列表
     */
    @RequiresPermissions("voucher:summary:list")
    @GetMapping("/list")
    public TableDataInfo list(Summary summary) {
        startPage();
        List<Summary> list = summaryService.selectSummaryList(summary);
        return getDataTable(list);
    }

    /**
     * 导出常用摘要列表
     */
    @RequiresPermissions("voucher:summary:export")
    @Log(title = "常用摘要", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Summary summary) {
        List<Summary> list = summaryService.selectSummaryList(summary);
        ExcelUtil<Summary> util = new ExcelUtil<Summary>(Summary.class);
        util.exportExcel(response, list, "常用摘要数据");
    }

    /**
     * 获取常用摘要详细信息
     */
    @RequiresPermissions("voucher:summary:query")
    @GetMapping(value = "/{summaryId}")
    public AjaxResult getInfo(@PathVariable("summaryId") Long summaryId) {
        return success(summaryService.selectSummaryBySummaryId(summaryId));
    }

    /**
     * 新增常用摘要
     */
    @RequiresPermissions("voucher:summary:add")
    @Log(title = "常用摘要", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated Summary summary) {
        return toAjax(summaryService.insertSummary(summary));
    }

    /**
     * 修改常用摘要
     */
    @RequiresPermissions("voucher:summary:edit")
    @Log(title = "常用摘要", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Summary summary) {
        if (summary.getSummaryId() == null) {
            throw new RuntimeException("凭证字ID不能为空");
        }
        return toAjax(summaryService.updateSummary(summary));
    }

    /**
     * 删除常用摘要
     */
    @RequiresPermissions("voucher:summary:remove")
    @Log(title = "常用摘要", businessType = BusinessType.DELETE)
    @DeleteMapping("/{summaryIds}")
    public AjaxResult remove(@PathVariable Long[] summaryIds) {
        if (summaryIds == null || summaryIds.length == 0) {
            throw new RuntimeException("请选择要删除的凭证字");
        }
        return toAjax(summaryService.deleteSummaryBySummaryIds(summaryIds));
    }
}
